/* ------------------------------------------------------------------------*
 *
 * ------------------------------------------------------------------------*/

#include "bsp.h"
#include "pincfg.h"
#include "os_obj.h"
#include "mbapp.h"
#include "com_def.h"
#include "bsp_cpu_it.h"
#include "bsp_uart_timer.h"
#include "pincfg.h"

//针对IO模块，超时改为50ms
#define qc_port UART8
#define qc_uart_irqn UART8_IRQn
#define qc_isr QC_UART8_IRQHandler
#define qc_obj mb.qc08
#define qc_cmd_list mb.qc_cmd08

// RS485 Dir-Pin
#define qc_rx_enable()
#define qc_tx_enable()

#include "bsp_qcom_gen.c"
qcom_api_make(USART8, qc_obj);

/*****************************************************************************
 * @brief   mb port.
 * @param   none
 * @return  none
 * @ Pass/ Fail criteria: none
 *****************************************************************************/
static void qc_port_hal_cfg(void)
{
	intx_alloc();

	nvic_irq_set(qc_uart_irqn, 0x0F, 0);

	intx_disable();

	crm_periph_clock_enable(CRM_UART8_PERIPH_CLOCK, TRUE);
	crm_periph_reset(CRM_UART8_PERIPH_RESET, TRUE);
	crm_periph_reset(CRM_UART8_PERIPH_RESET, FALSE);

	intx_enable();
}

/*****************************************************************************
 * @brief   mb_cb_set
 * @param   none
 * @return  none
 * @ Pass/ Fail criteria: none
 *****************************************************************************/
extern uu16 hdat[16];
static qc_com_slave_type qc_com_slave = {
	qc_reg_set,
	qc_reg_get,
	hdat,
	hdat,
	8,
	8};

static qc_mb_slave_type qc_mb_slave = {
	qc_reg_set,
	qc_reg_get,
	qc_reg_get,
	qc_coil_dat_set,
	qc_coil_dat_get,
	qc_coil_dat_get,
};

static void qc_cb_set(void)
{
	intx_alloc();

	qc_obj_init(&qc_obj, qc_cmd_list, sizeof(qc_cmd_list) / sizeof(qc_cmd_list[0]), 4);

	(void)qc_com_slave;
	(void)qc_mb_slave;

	qc_obj.slave = &qc_com_slave;
	qcom_api_link(USART8, qc_obj);
}

static void qc_timer_run(void)
{
	qc_timer_handle(&qc_obj);
}

/*****************************************************************************
 * @brief   mb init .
 * @param   mbMode
 * @param   ulBaudRate
 * @param   eParity
 * @return  none
 * @ Pass/ Fail criteria: none
 *****************************************************************************/
void qc08_Init(uu8 qcMode, uint32_t ulBaudRate, mb_parity_type eParity)
{
	// 禁用中断
	nvic_irq_set(qc_uart_irqn, 0x0F, 0);
	uart_timer.uart08 = 0;

	// 中断映射
	cpu_it.uart08 = qc_isr;

	// 初始化
	qc_port_Init(qcMode, ulBaudRate, eParity);

	// 链接定时器任务
	uart_timer.uart08 = qc_timer_run;
	app_timer_task_add(uart08_timer_handle);
}
